<template>
  <div class="feedback-pagination">
    <div class="btns-fun-field">
      <el-button type="primary" @click.prevent="showAddEditDialog" :icon="Plus">
        新增轮播图
      </el-button>

    </div>
    <el-table :data="tableData" stripe style="width: 100%" :v-loading="tableLoading" border>
      <el-table-column prop="name" label="名称" width="140" />
      <el-table-column prop="url" label="图片" width="100">
        <template #default="scoped">
          <el-image style="height: 60px" 
            :preview-src-list="[scoped.row.url]" 
            :preview-teleported="true"
            :src="scoped.row.url" fit="cover" />
        </template>
      </el-table-column>
      <el-table-column prop="url" label="url" min-width="220" >
        <template #default="scoped">
          <div style="overflow: hidden;text-overflow:ellipsis; white-space: nowrap;">{{ scoped.row.url }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="target" label="目标类型" width="120" >
        <template #default="scope">
          <span v-if="scope.row.target">{{ scope.row.target }}</span>
          <span v-else>--</span>
        </template>
      </el-table-column>
      <el-table-column prop="targetId" label="详情id" width="120" >
        <template #default="scope">
          <span v-if="scope.row.targetId">{{ scope.row.targetId }}</span>
          <span v-else>--</span>
        </template>
      </el-table-column>
      <el-table-column prop="sort" label="排序" width="60" />
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column label="操作" min-width="80px" fixed="right">
        <template #default="scope">
          <el-button type="danger" size="small" @click.prevent="showRemoveDialog(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-field">
        <el-pagination v-model:current-page="formData.pageIndex" v-model:page-size="formData.pageSize"
          :page-sizes="[10, 20, 30, 40]" :background="true" layout="total, sizes, prev, pager, next, jumper"
          :total="formData.total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>

    <el-dialog v-if="removeDialogVisible" v-model="removeDialogVisible" title="删除轮播图" width="400px">
      <div style="color: #f00">确定要删除当前轮播图？</div>
      <template #header>
        <div style="font-weight: bold">删除轮播图</div>
      </template>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="default" @click="removeDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="startRemoveDevice"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>


    <el-dialog v-model="addDialogVisible" :title="addEditForm.title" width="650px">
      <div style="padding-right: 50px">
        <el-form :model="addEditForm" :rules="addEditRules" ref="addEditRef" :label-width="120">
          <el-form-item label="名称" prop="name">
            <el-input v-model="addEditForm.name" autocomplete="off" placeholder="请输入名称" />
          </el-form-item>
          <el-form-item label="目标" prop="target">
            <el-input v-model="addEditForm.target" autocomplete="off" placeholder="请输入目标,用于APP区别类型" />
          </el-form-item>
          <el-form-item label="目标id" prop="targetId">
            <el-input v-model="addEditForm.targetId" autocomplete="off" placeholder="请输入目标ID,用于详情跳转" />
          </el-form-item>
          <el-form-item label="展示顺序" prop="sort">
            <el-input type="number" v-model="addEditForm.sort" autocomplete="off" placeholder="输入整数，表示轮播图显示顺序，从小到大排序" />
          </el-form-item>
          <el-form-item label="轮播图片" prop="url">
            <div style="width: 100%" v-loading="uploadLoading">
              <el-upload v-if="!addEditForm.url" style="width: 100%;" ref="upload" class="upload-demo"
                :before-upload="canUpload" :http-request="handleUpload" :on-success="uploadSuccess"
                :on-error="uploadError" drag action="/deviceservice/mallDevice/batchAdd" name="excelFile"
                :headers="uploadHeaders">
                <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                <div class="el-upload__text">将文件拖到此处, 或<em>点击上传</em></div>
              </el-upload>
              <el-image v-else fit="cover" style="height: 197px;width:100%; border-radius: 4px;"
                :src="addEditForm.url"></el-image>
              <div class="el-upload__tip">只能上传 jpg/png 的格式的图片，且不超过20MB。</div>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="requestAddBanner"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue';
// getOssSignature, uploadOss 
import { getBannerPagination, removeBanner, addBanner} from "@/api/system-manage.api";
import { getOssPolicy } from '@/api/oss-upload.api'
import { ElMessage, UploadRawFile } from "element-plus";
import { Plus, UploadFilled } from "@element-plus/icons-vue";
import type { FormInstance } from "element-plus";
import axios from 'axios';
const formData = reactive({
  pageIndex: 1,
  pageSize: 10,
  total: 0
})

const addEditForm = reactive({
  title: '',
  name: '',
  target: '',
  targetId: '',
  url: '',
  sort: 0
});

const addEditRules = reactive({
  name: [
    { required: true, message: "请输入名称", trigger: "blur" },
    { min: 1, max: 30, message: "长度为1~30位", trigger: "blur" },
  ],
  url: [
    { required: true, message: "请选择轮播图图片", trigger: "blur" },
  ]
});

const uploadHeaders = {
  "token": localStorage.getItem("TOKEN")
}

const uploadLoading = ref(false);
const showAddEditDialog = () => {
  addEditForm.title = "新增轮播图";
  addDialogVisible.value = true;
  addEditForm.url = '';
  addEditForm.name = '';
  addEditForm.target = '';
  addEditForm.targetId = '';
  addEditForm.sort = 0;
};

const addEditRef = ref<FormInstance>();
const requestAddBanner = () => {
  let formData = {
    name: addEditForm.name,
    target: addEditForm.target,
    targetId: addEditForm.targetId,
    url: addEditForm.url,
    sort: addEditForm.sort
  }

  if (!addEditRef.value) return;
  addEditRef.value.validate((valid) => {
    if (!valid) {
      return;
    }
    addBanner(formData).then(() => {
      addDialogVisible.value = false;
      ElMessage({
        message: "新增成功",
        type: "success",
      });
      getDataList();
    }).catch(err => {
      addDialogVisible.value = false;
      ElMessage({
        message: err.msg || err,
        type: "error",
      });
    });
  });
}

const uploadError = (err: any) => {
  uploadLoading.value = false;
  ElMessage({
    message: err.msg || err,
    type: "error",
  });
};

const uploadSuccess = () => {
  uploadLoading.value = false;
  ElMessage({
    message: "图片上传成功",
    type: "success",
  });

  addEditRef.value?.validateField("url");
  return;
};

const canUpload = async (rawFile: UploadRawFile) => {
  uploadLoading.value = true;
  let name = rawFile.name;
  let index = name.indexOf(".");
  let exet = name.substring(index + 1);
  if (!(exet === "jpg" || exet === 'png' || exet === "jpeg" || exet==='webp')) {
    ElMessage({
      message: "只能接受 jpg/png/webp 格式的图片文件",
      type: "error",
    });
    return false;
  }
  return true;
};

const handleUpload = async (option: any) => {

  //生成随机的图片文件名称。
  console.log("option: ", option)
  let fileName = option.file.name;
  let index = fileName.lastIndexOf(".");
  fileName.substring(index + 1);
  let res: {
        host: string,
        accessid: string,
        policy: string,
        signature: string,
        dir: string
        expire: string
  } = <any>await getOssPolicy();
  let url: string = res.host;
  let formData = new FormData();
  formData.append("OSSAccessKeyId", res.accessid);
  formData.append("policy", res.policy);
  formData.append("Signature", res.signature);
  formData.append("key", `${res.dir}${fileName}`);
  formData.append("expire", res.expire);
  formData.append("success_action_status", '200');
  formData.append("file", option.file);

  try {
    await axios.post(url, formData);
    addEditForm.url = `${url}/${res.dir}${fileName}`;
    console.log("handleUpload: ", res)
  } catch( err ){
    console.log(err)
  }

}


const tableLoading = ref(false);
const addDialogVisible = ref(false);
const tableData = ref([]);
const curSelectRow = ref({
  id: ''
});
const removeDialogVisible = ref(false);
const showRemoveDialog = (item: any) => {
  removeDialogVisible.value = true;
  curSelectRow.value = item;
  console.log("item: ", item);
};

const startRemoveDevice = () => {
  let id = curSelectRow.value.id;
  removeBanner([id])
    .then(() => {
      console.log("success~~~~~");
      removeDialogVisible.value = false;
      ElMessage({
        message: "轮播图删除成功",
        type: "success",
      });
      getDataList();
    })
    .catch((err) => {
      removeDialogVisible.value = false;
      ElMessage({
        message: err.msg || err,
        type: "error",
      });
    });
};


const handleSizeChange = (value: number) => {
  console.log("handleSizeChange...", value);
  formData.pageSize = value;
  getDataList();
};

const handleCurrentChange = (value: number) => {
  console.log("handleCurrentChange...", value);
  formData.pageIndex = value;
  getDataList();
};


const getDataList = () => {
  tableLoading.value = true;
  getBannerPagination({}).then(function (res: any) {
    tableLoading.value = false;
    tableData.value = res.list  || []
    formData.total = Number(res.total);
  }).catch(error => {
    console.log(error)
    tableLoading.value = false;
  })
}

onMounted(() => {
  getDataList();
})

</script>
<style lang="scss" scoped>
.feedback-pagination {
  margin-top: 8px;
}
.btns-fun-field {
  margin-bottom: 20px;
  ::v-deep(.el-button) {
    display: flex;
    align-items: center;

    .el-icon {
      width: 16px;
      height: 16px;
      padding: 1px !important;
      margin-bottom: 3px;
      font-weight: bolder;
    }

  }
}

.pagination-field {
  display: flex;
  justify-content: flex-end;
  margin: 20px 0;
}

.feedback-pagination {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
}

.el-upload__tip {
  margin: 0;
}

::v-deep(.el-upload-list) {
  display: none;
}
</style>
  